<template>
  <div class="search-container">
    <div>
      <a-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        layout="inline"
        @submit="handleSearch"
      >
        <a-form-item field="rangeValue" label="时间范围">
          <a-range-picker
            show-time
            :time-picker-props="{ defaultValue: ['00:00:00', '23:59:59'] }"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="formData.rangeValue"
            :shortcuts="rangeShortcuts"
            shortcuts-position="left"
          />
        </a-form-item>
        <a-form-item field="itemName" label="物品名称">
          <a-input v-model="formData.itemName" placeholder="物品名称" />
        </a-form-item>
        <a-form-item>
          <a-button html-type="submit" type="primary" :loading="searchLoading"
            >搜索</a-button
          >
        </a-form-item>
        <a-form-item>
          <a-button @click="handleTotalPrice">计算总价</a-button>
        </a-form-item>
        <a-form-item>
          <a-tag color="red" class="ml12" size="large">
            总计: {{ totalCount }}
          </a-tag>
          <a-tag color="red" class="ml12" size="large">
            ¥: {{ totalYuan }}
          </a-tag>
        </a-form-item>
      </a-form>
    </div>
    <div class="search-table mt20">
      <a-table
        :columns="columns"
        :data="tabelList"
        :pagination="false"
        :virtual-list-props="{
          height: height,
        }"
        :scroll="{
          x: 1470,
        }"
        size="medium"
        @sorterChange="handleSorterChange"
      >
        <template
          #name-filter="{
            filterValue,
            setFilterValue,
            handleFilterConfirm,
            handleFilterReset,
          }"
        >
          <div class="custom-filter">
            <a-space direction="vertical">
              <a-input
                :model-value="filterValue[0]"
                @input="(value:string) => setFilterValue([value])"
              />
              <div class="custom-filter-footer">
                <a-button @click="handleFilterConfirm">确定</a-button>
                <a-button class="ml12" @click="handleFilterReset"
                  >重置</a-button
                >
              </div>
            </a-space>
          </div>
        </template>
        <template #create_time="{ record }">
          {{ formatDate(record.create_time) }}
        </template>
        <template #isShiny="{ record }">
          <a-tag v-if="record.isShiny" color="red">是</a-tag>
          <a-tag v-else color="green">否</a-tag>
        </template>
        <template #buyer_account="{ record }">
          <a-tag v-if="record.buyer_account === '1'" color="green">
            系统回收
          </a-tag>
          <span v-else>{{ record.buyer_account }}</span>
        </template>
        <template #total_price="{ record }">
          <span v-html="formatPrice(record.total_price)"></span>
        </template>
        <template #itemDesc="{ record }">
          <div class="item-desc" v-if="record.item_type === 1">
            <a-tag :color="record.itemDesc.level === 100 ? 'red' : 'green'"
              >等级 {{ record.itemDesc.level }}</a-tag
            >
            <a-tag color="green">个体 {{ record.itemDesc.iv }}</a-tag>
            <a-tag color="arcoblue">性格 {{ record.itemDesc.nature }}</a-tag>
            <a-tag
              color="red"
              v-if="
                record.itemDesc.ability && record.itemDesc.ability !== '无特性'
              "
            >
              特性 {{ record.itemDesc.ability }}
            </a-tag>
            <a-tag color="purple" v-if="record.itemDesc.addMaxHP">
              额外HP {{ record.itemDesc.addMaxHP }}
            </a-tag>
          </div>
        </template>
        <template #learning_power="{ record }">
          <div class="item-desc" v-if="record.item_type === 1">
            <a-tag color="purple" v-if="record.itemDesc.evHp">
              体力 {{ record.itemDesc.evHp }}
            </a-tag>
            <a-tag color="purple" v-if="record.itemDesc.evAtk">
              攻击 {{ record.itemDesc.evAtk }}
            </a-tag>
            <a-tag color="purple" v-if="record.itemDesc.evDef"
              >防御 {{ record.itemDesc.evDef }}
            </a-tag>
            <a-tag color="purple" v-if="record.itemDesc.evSa"
              >特攻 {{ record.itemDesc.evSa }}
            </a-tag>
            <a-tag color="purple" v-if="record.itemDesc.evSd"
              >特防 {{ record.itemDesc.evSd }}
            </a-tag>
            <a-tag color="purple" v-if="record.itemDesc.evSp"
              >速度 {{ record.itemDesc.evSp }}
            </a-tag>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  shallowRef,
  useTemplateRef,
  onMounted,
  onUnmounted,
  computed,
} from 'vue'
import { searchByTime } from '@/api/search'
import to from '@/utils/to'
import { getColumns } from './config/config'
import { formatDate } from '@/utils/dayUtils'
import { formatPrice } from '@/utils/utils'
import {
  getTodayRange,
  getTwoDaysRange,
  getYesterdayRange,
} from '@/utils/dayUtils'
import emitter from '@/utils/mitt'
const { height } = defineProps<{
  height: number
}>()
const formRef = useTemplateRef('formRef')
const formData = ref({
  rangeValue: getTodayRange(),
  itemName: '',
})
const totalCount = ref(0)
const handleTotalPrice = () => {
  totalCount.value = tabelList.value.reduce((acc, item) => {
    return acc + Number(item.quantity)
  }, 0)
}
const totalYuan = computed(() => {
  return totalCount.value * 10
})
const rangeShortcuts = ref([
  {
    label: '今日',
    value: () => getTodayRange(),
  },
  {
    label: '昨日',
    value: () => getYesterdayRange(),
  },
  // 两天
  {
    label: '两天内',
    value: () => getTwoDaysRange(),
  },
])
const searchLoading = ref(false)
const config = {
  filter: (value: string, record: anyObj, key: string) => {
    const recordValue = record[key] + ''.trim()
    const trimValue = value + ''.trim()
    return recordValue.includes(trimValue)
  },
}
const columns = ref(getColumns(config))
const rules = {
  rangeValue: [{ required: true, message: '请选择时间范围' }],
}
// 冻结的列表
const tabelList = shallowRef<SearchTableRow[]>([])
let originList: SearchTableRow[] = []
const handleSearch = async () => {
  const errors = await formRef.value.validate()
  if (errors) return
  searchLoading.value = true
  const [res] = await to(
    searchByTime(
      formData.value.rangeValue[0],
      formData.value.rangeValue[1],
      formData.value.itemName
    )
  )
  if (res) {
    const data = res.data
    originList = data.map((item: SearchTableRow) => {
      return {
        ...item,
        itemDesc: JSON.parse(item.item_desc) as SearchTableRow['itemDesc'],
      }
    })
    tabelList.value = [...originList]
  }
  searchLoading.value = false
}
const sortList = (sorter: string, type: string) => {
  if (type === 'ascend') {
    let newList = tabelList.value.sort((a: any, b: any) => {
      return Number(a[sorter]) - Number(b[sorter])
    })
    tabelList.value = [...newList]
  } else if (type === 'descend') {
    let newList = tabelList.value.sort((a: any, b: any) => {
      return Number(b[sorter]) - Number(a[sorter])
    })
    tabelList.value = [...newList]
  } else {
    tabelList.value = [...originList]
  }
}
const handleSorterChange = (sorter: string, type: string) => {
  sortList(sorter, type)
}
const renderTable = () => {
  columns.value = getColumns(config)
}
onMounted(() => {
  emitter.on('renderTable', renderTable)
})
onUnmounted(() => {
  emitter.off('renderTable', renderTable)
})
</script>

<style scoped lang="scss">
.item-desc {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
</style>
